//
//  FeedbackViewController.m
//  Civacrm
//
//  Created by zhk on 2017/2/7.
//  Copyright © 2017年 王桂敏. All rights reserved.
//
#define kSpace 10
#import "FeedbackViewController.h"
#import "TZImagePickerController.h"
#import "HUPhotoBrowser.h"

@interface FeedbackViewController ()<UITextFieldDelegate,UITextViewDelegate,TZImagePickerControllerDelegate,UIImagePickerControllerDelegate,UINavigationControllerDelegate>

@property (nonatomic , strong) UITextField * titleField;
@property (nonatomic , strong) UITextView * contentTextView;
@property (nonatomic , strong) UIButton * commitBtn;
@property (nonatomic , strong) UILabel * placeholder;

@property (nonatomic , strong) UIButton * addPhotoBtn;

@property (nonatomic , strong) NSMutableArray * imageArray;

@property (nonatomic , strong) TZImagePickerController * imagePickerController;

@property (nonatomic , strong) UIImagePickerController * imagePickerC;

@end

@implementation FeedbackViewController

-(NSMutableArray *)imageArray
{
    if (!_imageArray) {
        _imageArray = [NSMutableArray array];
    }
    return _imageArray;
}

-(UIButton *)addPhotoBtn
{
    if (!_addPhotoBtn) {
        _addPhotoBtn = [[UIButton alloc]init];
        [_addPhotoBtn addTarget:self action:@selector(addPhoto) forControlEvents:(UIControlEventTouchUpInside)];
        [_addPhotoBtn setImage:[UIImage imageNamed:@"btn_add_photo"] forState:(UIControlStateNormal)];
        _addPhotoBtn.imageView.contentMode = UIViewContentModeScaleToFill;
        [self.view addSubview:_addPhotoBtn];
    }
    return _addPhotoBtn;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigation];
    [self initView];
}

- (void)initNavigation
{
    self.title = @"意见反馈";
    [self.rightButton setTitle:@"确定" forState:(UIControlStateNormal)];
    [self.rightButton setTitleColor:[UIColor whiteColor] forState:(UIControlStateNormal)];
}

- (void)initView
{
    self.view.backgroundColor = ColorWithHexString(@"f2f9fa");
    self.view.userInteractionEnabled = YES;
    self.titleField = [[UITextField alloc]init];
    [self.view addSubview:self.titleField];
    self.titleField.backgroundColor = [UIColor whiteColor];
    self.titleField.placeholder = @" 您要反馈的问题是？（必填）";
    self.titleField.returnKeyType = UIReturnKeyDone;
    self.titleField.delegate = self;
    [self.titleField setValue:ColorWithHexString(@"a0c0d2") forKeyPath:@"_placeholderLabel.textColor"];
    [self.titleField setValue:font(28) forKeyPath:@"_placeholderLabel.font"];
    [self.titleField mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.top.right.equalTo(self.view);
        make.height.offset(50);
    }];
    
    UILabel * lineLabel = [[UILabel alloc]init];
    [self.titleField addSubview:lineLabel];
    lineLabel.backgroundColor = GlobalBgColor;
    [lineLabel mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.equalTo(self.titleField);
        make.left.offset(10);
        make.bottom.offset(-1);
        make.height.offset(1);
    }];
    
    self.contentTextView = [[UITextView alloc]init];
    self.contentTextView.backgroundColor = [UIColor whiteColor];
    self.contentTextView.delegate = self;
    self.contentTextView.font = font(28);
    [self.view addSubview:self.contentTextView];
    [self.contentTextView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.equalTo(self.view);
        make.top.equalTo(self.titleField.mas_bottom);
        make.height.offset(356 / 2);
    }];
    
    self.placeholder = [[UILabel alloc]init];
    [self.contentTextView addSubview:self.placeholder];
    self.placeholder.textColor = ColorWithHexString(@"a0c0d2");
    self.placeholder.text = @"请详细描述您要反馈的问题";
    self.placeholder.font = font(28);
    [self.placeholder mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.offset(5);
        make.left.offset(5);
        make.size.mas_offset(CGSizeMake(180 * SizeZoom, 20 * SizeZoom));
    }];

    [self setupSelectedPhotos];
}

- (void)deletePicture:(UIButton *)sender
{
    if ([sender.superview isKindOfClass:[UIImageView class]]) {
        UIImageView * imageView = (UIImageView *)sender.superview;
        if (self.imageArray.count > 0) {
            [self.imageArray removeObjectAtIndex:sender.tag - 1000];
            [imageView removeFromSuperview];
        }
    }
    [self setupSelectedPhotos];
}

- (void)setupSelectedPhotos
{
    CGFloat imageWidthAndHeight = 60 * SizeZoom;
    NSInteger Count = self.imageArray.count;
    for (id object in [self.view subviews]) {
        if ([object isKindOfClass:[UIImageView class]]) {
            [object removeFromSuperview];
        }
    }
    if (Count == 8) {
        self.addPhotoBtn.hidden = YES;
    }else
    {
        self.addPhotoBtn.hidden = NO;
    }
    
    for (int i = 0; i < Count; i ++) {
        UIImageView * pictureImage = [[UIImageView alloc]init];
        [self.view addSubview:pictureImage];
        pictureImage.userInteractionEnabled = YES;
        pictureImage.image = self.imageArray[i];
        [pictureImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.left.offset(kSpace + (i % 4) * (kSpace + imageWidthAndHeight));
            make.top.equalTo(self.contentTextView.mas_bottom).offset(kSpace + i / 4 * (kSpace + imageWidthAndHeight));
            make.size.mas_offset(CGSizeMake(imageWidthAndHeight, imageWidthAndHeight));
        }];
        
        pictureImage.tag = 2000 + i;
        UITapGestureRecognizer * tapBigger = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(bigger:)];
        [pictureImage addGestureRecognizer:tapBigger];
        
        UIButton * deleteBtn = [[UIButton alloc]init];
        [pictureImage addSubview:deleteBtn];
        deleteBtn.tag = 1000 + i;
        //        删除图片过小 手指不容易点到
        [deleteBtn setImage:[UIImage imageNamed:@"icon_guanbizhaopian"] forState:(UIControlStateNormal)];
        [deleteBtn addTarget:self action:@selector(deletePicture:) forControlEvents:(UIControlEventTouchUpInside)];
        [deleteBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(pictureImage);
            make.right.equalTo(pictureImage);
            make.size.mas_offset(CGSizeMake(20 * SizeZoom, 20 * SizeZoom));  // 原来为35
        }];
    }
    [self.addPhotoBtn mas_updateConstraints:^(MASConstraintMaker *make) {
        make.left.offset(kSpace + Count % 4 * (kSpace + imageWidthAndHeight));
        make.top.equalTo(self.contentTextView.mas_bottom).offset(kSpace + Count / 4 * (kSpace + imageWidthAndHeight));
        make.size.mas_offset(CGSizeMake(60 * SizeZoom, 60 * SizeZoom));
    }];
    
}

- (void)bigger:(UITapGestureRecognizer *)tap
{
    [HUPhotoBrowser showFromImageView:(UIImageView *)tap.view withImages:self.imageArray atIndex:tap.view.tag - 2000];
}

- (void)addPhoto
{
    
    UIAlertController * alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction * actionLib = [UIAlertAction actionWithTitle:@"相册" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        self.imagePickerController = [[TZImagePickerController alloc]initWithMaxImagesCount:8 - self.imageArray.count delegate:self];
        [self.navigationController presentViewController:self.imagePickerController animated:YES completion:nil];
    }];
    UIAlertAction *cameraAction = [UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        self.imagePickerC = [[UIImagePickerController alloc]init];
        self.imagePickerC.sourceType = UIImagePickerControllerSourceTypeCamera;
        self.imagePickerC.delegate = self;
        self.imagePickerC.allowsEditing = YES;
        [self presentViewController:self.imagePickerC animated:YES completion:nil];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
    }];
    [alert addAction:actionLib];
    [alert addAction:cameraAction];
    [alert addAction:cancelAction];
    
    [self presentViewController:alert animated:YES completion:nil];
}

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info
{
    [self.imageArray addObject:info[UIImagePickerControllerEditedImage]];
    [self setupSelectedPhotos];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)imagePickerController:(TZImagePickerController *)picker didFinishPickingPhotos:(NSArray<UIImage *> *)photos sourceAssets:(NSArray *)assets isSelectOriginalPhoto:(BOOL)isSelectOriginalPhoto
{
    [self.imageArray addObjectsFromArray:photos];
    [self setupSelectedPhotos];
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)handleRightButtonAction:(UIButton *)sender
{
    if (self.titleField.text.length == 0) {
        
        [self showErrorWithStatus:@"请填写反馈标题"];
        
    }
//    else if (self.contentTextView.text.length == 0){
//        
//        [self showErrorWithStatus:@"请填写反馈内容"];
//        
//    }
    else
    {
        [self showIndeterminate];
        
        self.params[@"title"] = self.titleField.text;
        self.params[@"content"] = self.contentTextView.text;
        self.params[@"mobileVersion"] = [[UIDevice currentDevice] systemVersion];
        self.params[@"mobileModel"] = [self iphoneType];
        self.params[@"mobileManufacturers"] = @"Apple";
        self.params[@"terminalType"] = @"ios";
        self.params[@"sysVersion"] = @"1.0.0";
        NSMutableString * baseString = [NSMutableString string];
        for (int i = 0; i < self.imageArray.count; i ++) {
            NSData * data = UIImageJPEGRepresentation(self.imageArray[i], 0.1);
            NSMutableString * string = [data base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength].mutableCopy;
            if (i < self.imageArray.count - 1) {
                [string appendString:@","];
            }
            [baseString appendString:string];
        }
        self.params[@"pictures"] = baseString;
        
        [self.manager postWithURL:NET_Feedback param:self.params delegate:self isEncrypt:NO type:NetWorkingType0];
        
    }
}


- (void)networkingHandlefail:(NetworkingHandle *)handle type:(NetWorkingType)type
{
    [self hideHud];
    [self showErrorWithStatus:@"反馈失败，请重试"];
}

- (void)networkingHandleWarning:(NetworkingHandle *)handle responseObject:(id)responseObject type:(NetWorkingType)type
{
    [self hideHud];
    [self showErrorWithStatus:responseObject[@"returnInfo"]];
}

- (void)networkingHandleSuccess:(NetworkingHandle *)handle parameters:(NSDictionary *)parameters responseObject:(id)responseObject type:(NetWorkingType)type
{
    [self hideHud];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        [self showSuccessWithStatus:@"反馈成功，感谢您的反馈"];
        [self.navigationController popViewControllerAnimated:YES];
    });
}


- (void)textViewDidBeginEditing:(UITextView *)textView
{
    
    self.placeholder.hidden = YES;
    
}

- (void)textViewDidEndEditing:(UITextView *)textView
{
    if (textView.text.length == 0) {
        self.placeholder.hidden = NO;
    }
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [self.view endEditing:YES];
    return YES;
}

- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}



@end
